package com.yanyilu.basing.controller;


import com.yanyilu.basing.common.R;
import com.yanyilu.basing.entity.User;
import com.yanyilu.basing.jwt.JwtIgnore;
import com.yanyilu.basing.service.IUserService;
import com.yanyilu.basing.util.ParseJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Sxx
 * @since 2020-10-26
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 报名
     * @return
     */
    @PostMapping("/frontend/add")
    public R registe(@RequestBody @Validated User user){
        Integer userId = ParseJwtUtil.getUserId();
        user.setUserId(userId);
        //System.out.println("controller Addr==="+user.getShippingAddr());
        return userService.addUser(user);

    }

    /**
     *更新
     */
    @PostMapping("/frontend/update")
    public R updateUser(@RequestBody User user){
        Integer userId = ParseJwtUtil.getUserId();
        user.setUserId(userId);
        return userService.updateUser(user);
    }
    /**
     * 修改用户信息
     * @param user
     * @return
     */
   // @JwtIgnore
    @RequestMapping("/admin/update")
    public R AdminUpdateUser(@RequestBody User user){

        return userService.updateUser(user);
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
//    @JwtIgnore
    @RequestMapping("/admin/delete")
    public R AdminDeleteUser(@RequestParam("userId") Integer userId){

        return userService.AdminDeleteUser(userId);
    }

    /**
     * 用户列表
     * @param page
     * @param limit
     * @param userName
     * @param contactDetails
     * @return
     */
//    @JwtIgnore
    @RequestMapping("/admin/list")
    public R adminList(@RequestParam("page") Integer page,
                       @RequestParam("limit") Integer limit,
                       @RequestParam(value = "userName" ,required = false) String userName,
                       @RequestParam(value = "contactDetails" ,required = false) String contactDetails){

//        String role = ParseJwtUtil.getRole();

//        if(role.equals("0")){
        if(!(null!=userName)){
            userName = "";
        }
        if(!(null!=contactDetails)){
            contactDetails = "";
        }
        return userService.selectByAdminList(page,limit,userName,contactDetails);
//        }else {
//            return R.ok(ResultCode.NO_ROLE_ERROR);
//        }

    }

    @JwtIgnore
    @RequestMapping("/frontend/count")
    public R countPersonNum(){
        return userService.countNum();
    }

    @GetMapping("/frontend/info")
    public R getInfo(){
        Integer userId = ParseJwtUtil.getUserId();
        User user = userService.selectById(userId);
        return null != user ? R.ok().put("user",user) : R.ok().put("user",null);
    }


}
